<template>
    <Teleport to="body">
        <Transition name="fade">
            <div 
                v-if="visible"
                class="preview-overlay"
                @click.self="closePreview"
            >
                <div class="preview-container">
                    <!-- 关闭按钮 -->
                    <button 
                        class="btn-close-preview"
                        @click="closePreview"
                        aria-label="关闭预览"
                    >
                        <i class="bi bi-x-lg"></i>
                    </button>

                    <!-- 图片信息 -->
                    <div class="preview-info">
                        <span class="preview-filename">{{ currentImage?.name }}</span>
                        <span class="preview-count">{{ currentIndex + 1 }} / {{ images.length }}</span>
                    </div>

                    <!-- 图片容器 -->
                    <div class="preview-image-wrapper">
                        <img 
                            v-if="currentImage"
                            :src="currentImage.base64"
                            :alt="currentImage.name"
                            class="preview-image"
                            :style="imageStyle"
                            @wheel.prevent="handleWheel"
                        >
                    </div>

                    <!-- 工具栏 -->
                    <div class="preview-toolbar">
                        <button 
                            class="btn btn-sm btn-light"
                            @click="zoomOut"
                            :disabled="scale <= 0.1"
                            title="缩小 (Shift + -)"
                        >
                            <i class="bi bi-zoom-out"></i>
                        </button>
                        
                        <span class="zoom-level">{{ Math.round(scale * 100) }}%</span>
                        
                        <button 
                            class="btn btn-sm btn-light"
                            @click="zoomIn"
                            :disabled="scale >= 5"
                            title="放大 (Shift + +)"
                        >
                            <i class="bi bi-zoom-in"></i>
                        </button>

                        <div class="toolbar-divider"></div>

                        <button 
                            class="btn btn-sm btn-light"
                            @click="rotateLeft"
                            title="左旋转 (Shift + ←)"
                        >
                            <i class="bi bi-arrow-counterclockwise"></i>
                        </button>

                        <button 
                            class="btn btn-sm btn-light"
                            @click="rotateRight"
                            title="右旋转 (Shift + →)"
                        >
                            <i class="bi bi-arrow-clockwise"></i>
                        </button>

                        <div class="toolbar-divider"></div>

                        <button 
                            class="btn btn-sm btn-light"
                            @click="resetTransform"
                            title="重置 (R)"
                        >
                            <i class="bi bi-arrow-repeat"></i> 重置
                        </button>

                        <div class="toolbar-divider"></div>

                        <button 
                            class="btn btn-sm btn-danger"
                            @click="deleteCurrentImage"
                            :disabled="!currentImage"
                            title="删除当前图片 (Delete)"
                        >
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>

                    <!-- 导航按钮 -->
                    <button 
                        v-if="images.length > 1"
                        class="btn-nav btn-nav-prev"
                        @click="prevImage"
                        :disabled="currentIndex === 0"
                        title="上一张 (←)"
                    >
                        <i class="bi bi-chevron-left"></i>
                    </button>

                    <button 
                        v-if="images.length > 1"
                        class="btn-nav btn-nav-next"
                        @click="nextImage"
                        :disabled="currentIndex === images.length - 1"
                        title="下一张 (→)"
                    >
                        <i class="bi bi-chevron-right"></i>
                    </button>
                </div>
            </div>
        </Transition>
    </Teleport>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

interface FileItem {
    id: number
    name: string
    size: number
    type: string
    base64: string
    uploadedAt: Date
}

interface Props {
    visible: boolean
    images: FileItem[]
    initialIndex?: number
}

const props = withDefaults(defineProps<Props>(), {
    initialIndex: 0
})

const emit = defineEmits<{
    close: []
    'update:visible': [value: boolean]
    deleteImage: [payload: { id: number; nextIndex: number }]
}>()

const currentIndex = ref(props.initialIndex)
const scale = ref(1)
const rotation = ref(0)

const currentImage = computed(() => props.images[currentIndex.value])

const imageStyle = computed(() => ({
    transform: `scale(${scale.value}) rotate(${rotation.value}deg)`,
    transition: 'transform 0.3s ease'
}))

// 关闭预览
const closePreview = () => {
    emit('update:visible', false)
    emit('close')
    resetTransform()
}

// 缩放控制
const zoomIn = () => {
    if (scale.value < 5) {
        scale.value = Math.min(scale.value + 0.2, 5)
    }
}

const zoomOut = () => {
    if (scale.value > 0.1) {
        scale.value = Math.max(scale.value - 0.2, 0.1)
    }
}

// 鼠标滚轮缩放
const handleWheel = (e: WheelEvent) => {
    if (e.deltaY < 0) {
        zoomIn()
    } else {
        zoomOut()
    }
}

// 旋转控制
const rotateLeft = () => {
    rotation.value -= 90
}

const rotateRight = () => {
    rotation.value += 90
}

// 重置变换
const resetTransform = () => {
    scale.value = 1
    rotation.value = 0
}

// 删除当前图片
const deleteCurrentImage = () => {
    if (!currentImage.value) {
        return
    }

    const isLastImage = props.images.length === 1
    const nextIndex = currentIndex.value === props.images.length - 1
        ? Math.max(currentIndex.value - 1, 0)
        : currentIndex.value

    emit('deleteImage', {
        id: currentImage.value.id,
        nextIndex
    })

    if (!isLastImage) {
        currentIndex.value = nextIndex
        resetTransform()
    }
}

// 导航控制
const prevImage = () => {
    if (currentIndex.value > 0) {
        currentIndex.value--
        resetTransform()
    }
}

const nextImage = () => {
    if (currentIndex.value < props.images.length - 1) {
        currentIndex.value++
        resetTransform()
    }
}

// 键盘快捷键
const handleKeydown = (e: KeyboardEvent) => {
    if (!props.visible) return

    switch (e.key) {
        case 'Escape':
            closePreview()
            break
        case 'ArrowLeft':
            if (e.shiftKey) {
                rotateLeft()
            } else {
                prevImage()
            }
            break
        case 'ArrowRight':
            if (e.shiftKey) {
                rotateRight()
            } else {
                nextImage()
            }
            break
        case '+':
        case '=':
            if (e.shiftKey) {
                zoomIn()
            }
            break
        case '-':
        case '_':
            if (e.shiftKey) {
                zoomOut()
            }
            break
        case 'r':
        case 'R':
            resetTransform()
            break
        case 'Delete':
        case 'Backspace':
            deleteCurrentImage()
            break
    }
}

// 监听 visible 变化，重置索引
watch(() => props.visible, (newVal) => {
    if (newVal) {
        currentIndex.value = props.initialIndex
        document.body.style.overflow = 'hidden'
    } else {
        document.body.style.overflow = ''
    }
})

// 监听图片列表长度变化，确保索引有效
watch(() => props.images.length, (newLength) => {
    if (newLength === 0) {
        closePreview()
        return
    }

    if (currentIndex.value >= newLength) {
        currentIndex.value = newLength - 1
        resetTransform()
    }
})

// 生命周期
onMounted(() => {
    window.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
    window.removeEventListener('keydown', handleKeydown)
    document.body.style.overflow = ''
})
</script>

<style scoped>
.preview-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.95);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
}

.preview-container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

/* 关闭按钮 */
.btn-close-preview {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 40px;
    height: 40px;
    border: none;
    background-color: rgba(255, 255, 255, 0.1);
    color: white;
    border-radius: 50%;
    cursor: pointer;
    font-size: 1.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    z-index: 10;
}

.btn-close-preview:hover {
    background-color: rgba(255, 255, 255, 0.2);
    transform: scale(1.1);
}

/* 图片信息 */
.preview-info {
    position: absolute;
    top: 20px;
    left: 20px;
    color: white;
    display: flex;
    flex-direction: column;
    gap: 5px;
    z-index: 10;
    background-color: rgba(0, 0, 0, 0.5);
    padding: 10px 15px;
    border-radius: 8px;
}

.preview-filename {
    font-size: 1rem;
    font-weight: 500;
}

.preview-count {
    font-size: 0.875rem;
    color: rgba(255, 255, 255, 0.7);
}

/* 图片容器 */
.preview-image-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    padding: 80px 100px;
}

.preview-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    cursor: grab;
    user-select: none;
}

.preview-image:active {
    cursor: grabbing;
}

/* 工具栏 */
.preview-toolbar {
    position: absolute;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    gap: 10px;
    background-color: rgba(0, 0, 0, 0.7);
    padding: 12px 20px;
    border-radius: 30px;
    z-index: 10;
}

.preview-toolbar .btn-light {
    border: none;
    background-color: rgba(255, 255, 255, 0.9);
    padding: 6px 12px;
    transition: all 0.2s;
}

.preview-toolbar .btn-light:hover:not(:disabled) {
    background-color: white;
    transform: scale(1.05);
}

.preview-toolbar .btn-light:disabled {
    opacity: 0.4;
    cursor: not-allowed;
}

.preview-toolbar .btn-danger {
    border: none;
    padding: 6px 12px;
    transition: all 0.2s;
    background-color: rgba(220, 53, 69, 0.9);
    color: white;
}

.preview-toolbar .btn-danger:hover:not(:disabled) {
    background-color: rgba(220, 53, 69, 1);
    transform: scale(1.05);
}

.preview-toolbar .btn-danger:disabled {
    opacity: 0.4;
    cursor: not-allowed;
}

.zoom-level {
    color: white;
    font-size: 0.875rem;
    min-width: 50px;
    text-align: center;
}

.toolbar-divider {
    width: 1px;
    height: 24px;
    background-color: rgba(255, 255, 255, 0.3);
}

/* 导航按钮 */
.btn-nav {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 50px;
    height: 50px;
    border: none;
    background-color: rgba(255, 255, 255, 0.1);
    color: white;
    border-radius: 50%;
    cursor: pointer;
    font-size: 1.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    z-index: 10;
}

.btn-nav:hover:not(:disabled) {
    background-color: rgba(255, 255, 255, 0.2);
    transform: translateY(-50%) scale(1.1);
}

.btn-nav:disabled {
    opacity: 0.3;
    cursor: not-allowed;
}

.btn-nav-prev {
    left: 20px;
}

.btn-nav-next {
    right: 20px;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

/* 响应式 */
@media (max-width: 768px) {
    .preview-image-wrapper {
        padding: 60px 20px 120px;
    }

    .preview-info {
        top: 10px;
        left: 10px;
        font-size: 0.875rem;
        padding: 8px 12px;
    }

    .btn-close-preview {
        top: 10px;
        right: 10px;
        width: 35px;
        height: 35px;
    }

    .preview-toolbar {
        bottom: 20px;
        padding: 10px 15px;
        flex-wrap: wrap;
        max-width: 90%;
    }

    .btn-nav {
        width: 40px;
        height: 40px;
    }

    .btn-nav-prev {
        left: 10px;
    }

    .btn-nav-next {
        right: 10px;
    }
}
</style>
